import { login, NavSearch } from './tools.js'
import { APIGoodsList } from './fetch.js'

var keyword = '';
var size = 4;

$('.footer').load('../../layout/footer.html')
$('.header').load('../../layout/header.html', function () {
    $('.search').val(sessionStorage.search);
    login();
    NavSearch();
    
    if($('.search').val()){
        renderList({
            keyword:$('.search').val(),
            page: 1,
            size
        }, renderPage) 
    }

    $('.search-btn').click(function () {

        keyword = $('.search').val();

        // console.log(value);

        renderList({
            keyword,
            page: 1,
            size
        }, renderPage)

    })

    $('.cart').click(function(){
        location.href='../../html/cart.html'
      })

})


function renderList(data, cb) {
    APIGoodsList(data).then(({ data, count }) => {
        var html = '';
        $.each(data, (index, { img, gname, g_desc, price, gid }) => {
            html += `
            <a href="../../html/detail.html?gid=${gid}">     
             <div class="goodsList-goods">
            <div class="m">
               <img src="${img}" alt="">
            </div> 
           <p>${gname}</p>
           <span>￥${price}</span>
           </div> 
          </a>
                `
        });

        $('.goodsList-goods-w').html(html);

        cb && cb(count);
    })
}


function renderPage(count) {
    layui.laypage.render({
        elem: 'pagination',
        count,
        limit: size,
        jump: function (obj, first) {
            //obj包含了当前分页的所有参数，比如：
            // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
            // console.log(obj.limit); //得到每页显示的条数
            //首次不执行
            if (!first) {
                //do something
                renderList({
                    keyword,
                    page: obj.curr,
                    size
                })
            }
        }
    })
}
